#pragma once
#include <boost/shared_ptr.hpp>
#include <boost/enable_shared_from_this.hpp>
#include <boost/asio.hpp>
#include <map>
#include <queue>
#include "msg_base.h"
#include <json/json.h>
#include "net_handler.h"
#include <boost/thread/mutex.hpp>
#include <boost/thread/detail/singleton.hpp>
#include "hy_network_message.h"

using boost::asio::ip::tcp;


namespace hoyosvr
{
	class msg_bind
	{
	public:
		int								net_id;
		hy_network_message::ptr			msg;
	};
	namespace net
	{
		class tcp_session;
		class msg_server : 
			public boost::enable_shared_from_this<msg_server>,
			public net_handler
		{
		public:
			typedef boost::shared_ptr<hoyosvr::net::tcp_session>		tcp_session_ptr;
			typedef std::map<int,tcp_session_ptr>						client_map;					
			typedef	std::queue<msg_bind>								msg_queue;
			typedef boost::shared_ptr< net_handler>						net_handler_ptr;
			typedef boost::shared_ptr<tcp::acceptor>					acceptor_pointer;

			msg_server(void);
			virtual ~msg_server(void);

			void init();
			void run();
			void stop();

			inline bool is_stop() { return _is_stop;}

			virtual	void on_connect(int client_id,tcp_session_ptr conn_ptr);
			virtual	void on_disconnect(int client_id,tcp_session_ptr conn_ptr);
			virtual	void sync_process_recv_msg(int net_id,hy_network_message::ptr recv_msg_ptr);
			virtual	bool async_process_recv_msg(tcp_session_ptr conn,hy_network_message::ptr recv_msg_ptr);

			virtual void on_init();
			virtual	void on_update();
			virtual void on_stop(){}

			void send_msg(int client_id, hy_network_message& m);
			void send_msg(tcp_session_ptr conn_ptr,hy_network_message* m);
			void disconnect(int client_id);

			void recv_client_handler	(tcp_session_ptr session,const char* data_ptr,int len);
			void client_connect_handler	(tcp_session_ptr session,int error_value);

		private:
			void start_accept();
			void handle_accept(tcp_session_ptr new_connection,acceptor_pointer ap,const boost::system::error_code& error);
			void update();		
			
		protected:
			client_map				_map_client;
			Json::Value				_configs;
			msg_queue				_msg_queue;
			boost::mutex			_queue_mutex;
			boost::mutex			_client_mutex;
			acceptor_pointer		_acceptor_ptr;
			net_handler_ptr			_client_handler_ptr;

			int						_client_count;
			bool					_is_stop;
		};
	}
}




